package util

import (
	"bytes"
	"crypto/tls"
	"fmt"
	"go-chromedp-client/structs"
	"io"
	"io/ioutil"
	neturl "net/url"
	"strings"

	"net/http"
	"time"
)

// 发送GET请求
// url：         请求地址
// response：    请求返回的内容
func Get(url string, header []string, option structs.Options) (string, error) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Printf("%s\n", err)
		}
	}()
	var Timeout int64 = 30
	if int(option.Timeout) > 0 {
		Timeout = option.Timeout
	}
	var proxy_server string = option.Proxy
	// 超时时间：5秒
	client := &http.Client{Timeout: time.Duration(Timeout) * time.Second}
	req, _ := http.NewRequest("GET", url, nil)
	if option.Ua == "" {
		option.Ua = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
	}
	req.Header.Set("User-Agent", option.Ua)
	for _, v := range header {
		hh := strings.Split(v, ":")
		req.Header.Set(hh[0], hh[1])
	}

	if proxy_server != "" {
		uri, err := neturl.Parse(proxy_server)
		if err != nil {
			fmt.Println(42, err)
			return "", err
		}
		client.Transport = &http.Transport{
			Proxy:           http.ProxyURL(uri),
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
	} else {
		client.Transport = &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
	}
	resp, err := client.Do(req)
	//resp, err := client.Get(url)
	if err != nil {
		fmt.Println(52, err)
		return err.Error(), err
		//panic(err)
	}
	defer resp.Body.Close()
	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			fmt.Println(err)
			return err.Error(), err
			//panic(err)
		}
	}

	return result.String(), nil

}

// 发送POST请求
// url：         请求地址
// data：        POST请求提交的数据
// contentType： 请求体格式，如：application/json
// content：     请求放回的内容
func Post(url string, header []string, data string, option structs.Options) (string, error) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Printf("%s\n", err)
		}
	}()
	var proxy_server string = option.Proxy
	contentType := "application/json"
	if option.ContentType != "" {
		contentType = option.ContentType
	}

	var Timeout int64 = 30
	if int(option.Timeout) > 0 {
		Timeout = option.Timeout
	}
	// 超时时间：5秒
	client := &http.Client{Timeout: time.Duration(Timeout) * time.Second}
	//fmt.Println("data", data)
	var jsonStr string
	jsonStr = data

	req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(jsonStr)))
	req.Header.Set("Content-Type", contentType)

	for _, v := range header {
		hh := strings.Split(v, ":")
		req.Header.Set(hh[0], hh[1])
	}
	if err != nil {
		return "", err
	}
	if proxy_server != "" {
		uri, err := neturl.Parse(proxy_server)
		if err != nil {
			fmt.Println(err)
			return "", err
		}
		client.Transport = &http.Transport{
			Proxy:           http.ProxyURL(uri),
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
	} else {
		client.Transport = &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
	}
	if option.Debug == 1 {
		fmt.Println("contentType", contentType)
		fmt.Println("Header", req.Header)
		fmt.Println("HeaderContentType", req.Header.Get("Content-Type"))
		fmt.Println("HeaderAccept-Language", req.Header.Get("Accept-Language"))
		fmt.Println("jsonStr", string(jsonStr))
	}

	//client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return "", err
		//	panic(err)
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	return string(result), nil
}
func ApiHeader(w *http.ResponseWriter) {
	(*w).Header().Set("Access-Control-Allow-Origin", "http://spider.sumroads.site")
	(*w).Header().Add("Access-Control-Allow-Headers", "*")
	(*w).Header().Set("Access-Control-Allow-Methods", "*")
	(*w).Header().Add("Access-Control-Allow-Credentials", "true")

}
func ApiWrite(w *http.ResponseWriter, body []byte) {
	(*w).Write(body)
}
